package com.channel.temperature.collect.ui.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.HBluetooth
import com.hjy.bluetooth.exception.BluetoothException
import com.hjy.bluetooth.inter.SendCallBack
import com.hjy.bluetooth.operator.abstra.Sender
import com.channel.temperature.collect.R
import com.channel.temperature.collect.app.ext.LiveDataEvent
import com.channel.temperature.collect.app.ext.LiveDataEvent.checkedWorkMode
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.CRC16Utils
import com.channel.temperature.collect.app.util.MyUtil
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.data.response.SystemInfoBean
import com.channel.temperature.collect.data.response.TaskBean
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import me.hgj.mvvmhelper.base.BaseViewModel
import me.hgj.mvvmhelper.base.appContext
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date


class TaskModel : BaseViewModel() {
    var tasklistData = MutableLiveData<ArrayList<TaskBean>>()
    var clickType = 0
    var continueSendWakeUpCMD = true

    var dataResult: ByteArray = ByteArray(215)
    var otherPackageData = ByteArray(8)
    var taskDeviceName = ""
    var taskCurrentName = ""
    var taskDesc = ""
    var setIntervalTime = 0
    var setPressNumber = 0f
    var setInitCollectDelay = 0

    //原始值 通信地址1B 通信超时1b 唤醒间隔1b 工作模式1b 在线模式工作时长2b 在线工作间隔时间2b    0:空闲模式 1：离线模式 3：在线模式 2:压力模式
    var originalPackageData =
        byteArrayOf(0xFA.toByte(), 0x1E.toByte(), 0x0A.toByte(), 0x01, 0x07, 0x08, 0x00, 0x01)

    var sendTaskOrAutoTask = MutableLiveData<Int>() //2:发送任务  3:发送一键任务

    var waitSendTaskOtherData = ByteArray(215)//等待发送的其它值
    var waitSendTaskDataModeIs2 = ByteArray(215)//当当前模式为2 压力模式时临时保存的8个任务的值

    var checkTimeClick = -1 //1:发送任务的校时 2：一键发送任务的校时
    fun sendCommonCMD(mSender: Sender, value: String) {
        viewModelScope.launch {
            var bufData = MyUtil.hex2Bytes(value)
            Log.e("sendCommonCMD", "sendCommonCMD  " + value)
            sendCmdWithOutTime(bufData)
        }
    }

    fun sendTasksCMD(mSender: Sender) {
        viewModelScope.launch {
            var value = getSendCMDString()
            var bufData = MyUtil.hex2Bytes(value)
            Log.e("最终值", "最终值  " + value)
            sendCmdWithOutTime(bufData)

        }
    }

    fun sendAutoTasksCMD() {
        viewModelScope.launch {
            var value = getAutoTasksSendCMDString()
            var bufData = MyUtil.hex2Bytes(value)
            Log.e("最终值", "最终值  " + value)
            sendCmdWithOutTime(bufData)
        }
    }


    fun sendCmdWithOutTime(bufData: ByteArray) {
        HBluetooth.getInstance().sender().send(bufData, object : SendCallBack {
            override fun onSending(command: ByteArray) {
//                    addMessage("命令发送中... " + MyUtil.bytes2Hex(command))
            }

            override fun onSendFailure(bleException: BluetoothException) {
                Log.e("onSendFailure", "onSendFailure " + bleException.message.toString())
            }
        })
        viewModelScope.launch {
            val conditionIsTrue = withTimeoutOrNull(3000L) {
                repeat(3) { index ->
                    if (clickType == -1) {
                        return@withTimeoutOrNull true
                    }
                    delay(1000L)
                }
                false
            }
            conditionIsTrue?.let { isTrue ->
                Log.e(
                    "sendCmdWithOutTime", "最终条件是: $isTrue"
                )
            } ?: run {
                ToastUtils.show(appContext.resources.getString(R.string.out_time_tips))

                Log.e(
                    "sendCmdWithOutTime", "等待时间超时，未满足条件"
                )
            }
        }
    }

    public fun getTimeCMD(timeString: String): String {
        val format = SimpleDateFormat("yyMMddHHmmss")
        var str = format.format(MyUtil.StrToDate(timeString))
        Log.e("校时", "校时str  " + str)
        var year = MyUtil.numberToHexOne(str.substring(0, 2).toInt())
        var month = MyUtil.numberToHexOne(str.substring(2, 4).toInt())
        var day = MyUtil.numberToHexOne(str.substring(4, 6).toInt())
        var hour = MyUtil.numberToHexOne(str.substring(6, 8).toInt())
        var minute = MyUtil.numberToHexOne(str.substring(8, 10).toInt())
        var second = MyUtil.numberToHexOne(str.substring(10, 12).toInt())
        var timeResult = "" + year + month + day + hour + minute + second
        return timeResult
    }

    fun getAutoTasksSendCMDString(): String {
        var tempCMD = "FF55AA00D2" + getAddress() + "45020000000000C8"
        var cmd = ""
        var systemInfoBeanJson = mmkv.getString(ValueKey.SYSTEM_INFO, "")
        if (!systemInfoBeanJson.isNullOrEmpty()) {
            var mInfoBean = Gson().fromJson<Any>(
                systemInfoBeanJson, object : TypeToken<SystemInfoBean>() {}.type
            ) as SystemInfoBean
            Log.e("getSendCMDString", "getSendCMDString " + mInfoBean.toString())

            var currentTimeDate = Date()
            var oneYear = 365L * 24 * 60 * 60 * 1000
            var oneYearPlus7Month = oneYear + 210L * 24 * 60 * 60 * 1000
            var endTime = currentTimeDate.time + oneYearPlus7Month

            var currentTimeString = MyUtil.DateToStr(currentTimeDate)
            var endTimeString = MyUtil.DateToStr(Date(endTime))
            mmkv.putString(ValueKey.COLLECTION_START_TIME, currentTimeString)
            mmkv.putString(ValueKey.COLLECTION_END_TIME, endTimeString)

            var currentTimeCMDString = getTimeCMD(currentTimeString)
            var endTimeCMDString = getTimeCMD(endTimeString)
            mmkv.putString(ValueKey.COLLECTION_START_TIME_CMD, currentTimeCMDString)
            mmkv.putString(ValueKey.COLLECTION_END_TIME_CMD, endTimeCMDString)
            var originalPackageDataTemp = originalPackageData
            originalPackageDataTemp[3] = LiveDataEvent.checkedWorkMode.value?.toByte()!!
            cmd =
                cmd + MyUtil.bytes2Hex(originalPackageDataTemp) + currentTimeCMDString + endTimeCMDString

            if (LiveDataEvent.checkedWorkMode.value == 2) {
                var listDataTemp = ArrayList<TaskBean>()
                for (i in 0 until 8) {
                    if (i == 0) {
                        var taskTime = "" + setPressNumber
                        var bean = TaskBean(
                            taskTime = taskTime,
                            delayTime = setInitCollectDelay,
                            isSelected = false,
                            isRemote = false
                        )
                        listDataTemp.add(bean)
                    } else {
                        var taskTime = "" + 200
                        var bean = TaskBean(
                            taskTime = taskTime,
                            delayTime = setIntervalTime,
                            isSelected = false,
                            isRemote = false
                        )
                        listDataTemp.add(bean)
                    }


                }
                tasklistData.value = listDataTemp
                Log.e("cmd", "cmd 拼接 " + cmd)
                cmd += MyUtil.bytes2Hex(waitSendTaskDataModeIs2)
                cmd += "447A0000"
                for (i in 0 until listDataTemp.size) {
                    var bean = listDataTemp.get(i)
                    var time = "" + ((bean.taskTime.toFloat()) * 100).toInt()
                    var timeResult = "" + MyUtil.numberToHexTwo(time.toInt())
                    cmd = cmd + timeResult + MyUtil.numberToHexTwo(bean.delayTime)
                }
                Log.e("测试", "测试cmd   " + cmd)
                cmd += MyUtil.bytes2Hex(waitSendTaskOtherData)
                cmd = cmd + CRC16Utils.CHECKSUM(MyUtil.hex2Bytes(cmd)) + "5A" + "0000"
                tempCMD = tempCMD + cmd
                tempCMD = tempCMD + CRC16Utils.checkCRC(MyUtil.hex2Bytes(tempCMD))
            } else {
                var listDataTemp = ArrayList<TaskBean>()
                for (i in 0 until 8) {
                    var taskTime = currentTimeDate.time + oneYear + 30L * 24 * 60 * 60 * 1000 * i
                    var bean = TaskBean(
                        taskTime = MyUtil.DateToStr(Date(taskTime)),
                        delayTime = setIntervalTime,
                        isSelected = false,
                        isRemote = false
                    )
                    listDataTemp.add(bean)
                }
                tasklistData.value = listDataTemp
                Log.e("cmd", "cmd 拼接 " + cmd)
                for (i in 0 until listDataTemp.size) {
                    var bean = listDataTemp.get(i)
                    var time = bean.taskTime
                    val format = SimpleDateFormat("yyMMddHHmmss")
                    var str = format.format(MyUtil.StrToDate(time))
                    Log.e("校时", "校时str  " + str)
                    var year = MyUtil.numberToHexOne(str.substring(0, 2).toInt())
                    var month = MyUtil.numberToHexOne(str.substring(2, 4).toInt())
                    var day = MyUtil.numberToHexOne(str.substring(4, 6).toInt())
                    var hour = MyUtil.numberToHexOne(str.substring(6, 8).toInt())
                    var minute = MyUtil.numberToHexOne(str.substring(8, 10).toInt())
                    var second = MyUtil.numberToHexOne(str.substring(10, 12).toInt())
                    var timeResult = "" + year + month + day + hour + minute + second
                    cmd = cmd + timeResult + MyUtil.numberToHexTwo(bean.delayTime)
                }
                Log.e("测试", "测试cmd   " + cmd)
                cmd += "447A0000"
                cmd = cmd + MyUtil.bytes2Hex(waitSendTaskOtherData) + CRC16Utils.CHECKSUM(
                    MyUtil.hex2Bytes(
                        cmd
                    )
                ) + "5A" + "0000"
                tempCMD = tempCMD + cmd
                tempCMD = tempCMD + CRC16Utils.checkCRC(MyUtil.hex2Bytes(tempCMD))
            }

        } else {
            ToastUtils.show("本地暂无设备系统参数信息，请先连接设备后读取系统参数")
        }

        return tempCMD
    }

    fun getSendCMDString(): String {
        var tempCMD = "FF55AA00D2" + getAddress() + "45020000000000C8"
        var cmd = ""
        var systemInfoBeanJson = mmkv.getString(ValueKey.SYSTEM_INFO, "")
        if (!systemInfoBeanJson.isNullOrEmpty()) {
            var mInfoBean = Gson().fromJson<Any>(
                systemInfoBeanJson, object : TypeToken<SystemInfoBean>() {}.type
            ) as SystemInfoBean
            Log.e("getSendCMDString", "getSendCMDString " + mInfoBean.toString())
            var originalPackageDataTemp = originalPackageData
            originalPackageDataTemp[3] = LiveDataEvent.checkedWorkMode.value?.toByte()!!
            cmd = cmd + MyUtil.bytes2Hex(originalPackageDataTemp) + mmkv.getString(
                ValueKey.COLLECTION_START_TIME_CMD, "000000000000"
            ) + mmkv.getString(
                ValueKey.COLLECTION_END_TIME_CMD, "000000000000"
            )
            Log.e("cmd", "cmd 拼接 " + cmd)
            var listData = tasklistData.value
            if (LiveDataEvent.checkedWorkMode.value == 2) {

                Log.e("测试", "测试cmd   " + cmd)
                cmd += MyUtil.bytes2Hex(waitSendTaskDataModeIs2)
                cmd += "447A0000"

                for (i in 0 until listData?.size!!) {
                    var bean = listData.get(i)
                    var time = (bean.taskTime.toFloat()) * 100
                    var timeResult = "" + MyUtil.numberToHexTwo(time.toInt())
                    cmd = cmd + timeResult + MyUtil.numberToHexTwo(bean.delayTime)
                }
                cmd += MyUtil.bytes2Hex(waitSendTaskOtherData)
                cmd = cmd + CRC16Utils.CHECKSUM(MyUtil.hex2Bytes(cmd)) + "5A" + "0000"
                tempCMD = tempCMD + cmd
                tempCMD = tempCMD + CRC16Utils.checkCRC(MyUtil.hex2Bytes(tempCMD))
            } else {
                for (i in 0 until listData?.size!!) {
                    var bean = listData.get(i)
                    var time = bean.taskTime
                    val format = SimpleDateFormat("yyMMddHHmmss")
                    var str = format.format(MyUtil.StrToDate(time))
                    Log.e("校时", "校时str  " + str)
                    var year = MyUtil.numberToHexOne(str.substring(0, 2).toInt())
                    var month = MyUtil.numberToHexOne(str.substring(2, 4).toInt())
                    var day = MyUtil.numberToHexOne(str.substring(4, 6).toInt())
                    var hour = MyUtil.numberToHexOne(str.substring(6, 8).toInt())
                    var minute = MyUtil.numberToHexOne(str.substring(8, 10).toInt())
                    var second = MyUtil.numberToHexOne(str.substring(10, 12).toInt())
                    var timeResult = "" + year + month + day + hour + minute + second
                    cmd = cmd + timeResult + MyUtil.numberToHexTwo(bean.delayTime)
                }
                Log.e("测试", "测试cmd   " + cmd)
                cmd += "447A0000"
                cmd = cmd + MyUtil.bytes2Hex(waitSendTaskOtherData) + CRC16Utils.CHECKSUM(
                    MyUtil.hex2Bytes(
                        cmd
                    )
                ) + "5A" + "0000"
                tempCMD = tempCMD + cmd
                tempCMD = tempCMD + CRC16Utils.checkCRC(MyUtil.hex2Bytes(tempCMD))
            }

        } else {
            ToastUtils.show("本地暂无设备系统参数信息，请先连接设备后读取系统参数")
        }
//        var value = cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))

        return tempCMD
    }

    private fun getAddress(): String {
        return "FA"
    }

    private fun formatTimeString(time: String): String {
        var result = ""
        var year = "" + (2000 + time.substring(0, 2).toInt(16))
        var month = time.substring(2, 4).toInt(16)
        var day = time.substring(4, 6).toInt(16)
        var hour = time.substring(6, 8).toInt(16)
        var minute = time.substring(8, 10).toInt(16)
        var second = time.substring(10, 12).toInt(16)
        result = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
        return MyUtil.DateToStr(MyUtil.StrToDate(result))
    }

    var packageDataLength: Int = 0
    var resultDataLength: Int = 0
    var needFoldData = false
    fun handleBLEResult(data: ByteArray) {
        Log.e("handleBLEResult", "handleBLEResult  " + clickType)
        if (data.size > 2) {
            when (clickType) {
                //1:复位 2：关机 3：唤醒设备 4：进入休眠 5：校时 6：清空flash 7：读取存储数量 8:设备信息 9:读系统参数 10：写系统参数 15：发送任务名称 16：查询任务名称  17:一键设置发送任务名称
                //18：点击 发送任务 时查询当前连接设备的离线数据是已读还是未读
                //19 点击 一键启动 时查询当前连接设备的离线数据是已读还是未读
                //20 设置时间参数或者压力参数
                18 -> {
                    var packageData = data.copyOfRange(0, data.size - 1)
                    var result = CRC16Utils.checkCRC(packageData)
                    if (result.toInt(16) == java.lang.Byte.toUnsignedInt(data[data.size - 1])) {

                        var isRead = data[data.size - 2]
                        Log.e("handleBLEResult", "18 校验成功 " + isRead)
                        if (isRead == 1.toByte()) {
                            resetClickType()
                            viewModelScope.launch {
                                sendTaskOrAutoTask.value = 2
                            }
                        } else if (isRead == 0.toByte()) {
                            ToastUtils.show("当前任务数据未读取，请读取后再开启新的任务")
                            resetClickType()
                        } else {
                            resetClickType()
                            ToastUtils.show("命令校验失败")
                        }
                    } else {
                        resetClickType()
                        ToastUtils.show("命令校验失败")
                    }
                }

                19 -> {
                    var packageData = data.copyOfRange(0, data.size - 1)
                    var result = CRC16Utils.checkCRC(packageData)
                    if (result.toInt(16) == java.lang.Byte.toUnsignedInt(data[data.size - 1])) {

                        var isRead = data[data.size - 2]
                        Log.e("handleBLEResult", "19 校验成功 " + isRead)
                        if (isRead == 1.toByte()) {
                            resetClickType()
                            viewModelScope.launch {
                                sendTaskOrAutoTask.value = 3
                            }

                        } else if (isRead == 0.toByte()) {
                            ToastUtils.show("当前任务数据未读取，请读取后再开启新的任务")
                            resetClickType()

                        } else {
                            resetClickType()
                            ToastUtils.show("命令校验失败")
                        }
                    } else {
                        resetClickType()
                        ToastUtils.show("命令校验失败")
                    }
                }

                9 -> {
                    var hexResult = MyUtil.bytes2Hex(data.copyOfRange(0, 3))
                    if ("FF55AA" == hexResult) {
                        packageDataLength = 0
                        resultDataLength = MyUtil.bytes2Hex(data.copyOfRange(3, 5)).toInt(16)
                        dataResult = ByteArray(resultDataLength + 5)
                        needFoldData = data.size < resultDataLength + 5
                    }
                    if (needFoldData) {
                        System.arraycopy(data, 0, dataResult, packageDataLength, data.size)
                        packageDataLength += data.size
                        needFoldData = packageDataLength != resultDataLength + 5
                        if (packageDataLength == resultDataLength + 5) {
                            var packageData = dataResult.copyOfRange(0, dataResult.size - 1)
                            var result = CRC16Utils.checkCRC(packageData)

                            if (result.toInt(16) == java.lang.Byte.toUnsignedInt(dataResult[dataResult.size - 1])) {
                                handleTask(dataResult)
                            } else {
                                ToastUtils.show("命令校验失败")
                                resetClickType()
                            }

                        }
                    } else {
                        var packageData = data.copyOfRange(0, data.size - 1)
                        var result = CRC16Utils.checkCRC(packageData)
                        if (result.toInt(16) == java.lang.Byte.toUnsignedInt(data[data.size - 1])) {
                            handleTask(data)
                        } else {
                            resetClickType()
                            ToastUtils.show("命令校验失败")
                        }
                    }

                }

                10 -> {
                    viewModelScope.launch {
                        if (data.size > 13) {
                            var packageData = data.copyOfRange(0, data.size - 1)
                            var result = CRC16Utils.checkCRC(packageData)
                            if (result.toInt(16) == java.lang.Byte.toUnsignedInt(data[data.size - 1])) {
                                if (data[data.size - 2].toInt() == 0X5A) {
                                    LiveDataEvent.currentMode.value =
                                        LiveDataEvent.checkedWorkMode.value
                                    ToastUtils.show("设置成功")
                                }
                            }
                            resetClickType()
                        }
                    }
                }

                3 -> {
                    viewModelScope.launch {
                        if (data[data.size - 2].toInt() == 0x5A) {
                            Log.e("唤醒操作", "唤醒设备成功")
                            ToastUtils.show("唤醒设备成功")
                            continueSendWakeUpCMD = false
                            delay(500)

                            if (HBluetooth.getInstance().isConnected) {
                                needFoldData = false
                                HBluetooth.getInstance().sender()?.let { it1 ->
                                    clickType = 9
                                    var cmd = "FF55AA000A" + getAddress() + "45010000000000C8"
                                    sendCommonCMD(
                                        it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                                    )
                                }
                            } else {
                                ToastUtils.show("请先连接设备后再操作")
                            }
//                            queryTaskCMD()
                        } else if (data[data.size - 2].toInt() == 0xFF) {
                            Log.e("唤醒操作", "唤醒设备失败")
                        }

                    }

                }

                15 -> {
                    var hexResult = MyUtil.bytes2Hex(data.copyOfRange(0, 3))
                    viewModelScope.launch {
                        if ("FF55AA" == hexResult) {
                            packageDataLength = 0
                            resultDataLength = MyUtil.bytes2Hex(data.copyOfRange(3, 5)).toInt(16)
                            dataResult = ByteArray(resultDataLength + 5)
                            needFoldData = data.size < resultDataLength + 5
                        }
                        if (needFoldData) {
                            System.arraycopy(data, 0, dataResult, packageDataLength, data.size)
                            packageDataLength += data.size
                            needFoldData = packageDataLength != resultDataLength + 5
                            if (packageDataLength == resultDataLength + 5) {
                                var packageData = dataResult.copyOfRange(0, dataResult.size - 1)
                                var result = CRC16Utils.checkCRC(packageData)

                                if (result.toInt(16) == java.lang.Byte.toUnsignedInt(dataResult[dataResult.size - 1])) {
                                    clickType = 10
                                    delay(200)
                                    sendTasksCMD(HBluetooth.getInstance().sender())
                                } else {
                                    ToastUtils.show("命令校验失败")
                                }

                            }
                        } else {
                            var packageData = data.copyOfRange(0, data.size - 1)
                            var result = CRC16Utils.checkCRC(packageData)
                            if (result.toInt(16) == java.lang.Byte.toUnsignedInt(data[data.size - 1])) {
                                clickType = 10
                                delay(200)
                                sendTasksCMD(HBluetooth.getInstance().sender())
                            } else {

                                ToastUtils.show("命令校验失败")
                            }
                        }
                    }

                }

                16 -> {
                    viewModelScope.launch {
                        var hexResult = MyUtil.bytes2Hex(data.copyOfRange(0, 3))
                        if ("FF55AA" == hexResult) {
                            packageDataLength = 0
                            resultDataLength = MyUtil.bytes2Hex(data.copyOfRange(3, 5)).toInt(16)
                            dataResult = ByteArray(resultDataLength + 5)
                            needFoldData = data.size < resultDataLength + 5
                        }
                        if (needFoldData) {
                            System.arraycopy(data, 0, dataResult, packageDataLength, data.size)
                            packageDataLength += data.size
                            needFoldData = packageDataLength != resultDataLength + 5
                            if (packageDataLength == resultDataLength + 5) {
                                var packageData = dataResult.copyOfRange(0, dataResult.size - 1)
                                var result = CRC16Utils.checkCRC(packageData)

                                if (result.toInt(16) == java.lang.Byte.toUnsignedInt(dataResult[dataResult.size - 1])) {
                                    ToastUtils.show("查询成功")
                                    taskDeviceName =
                                        remove00(data.copyOfRange(14, 54)).toString(Charsets.UTF_8)
                                            .trim()
                                    taskCurrentName =
                                        remove00(data.copyOfRange(54, 94)).toString(Charsets.UTF_8)
                                            .trim()
                                    taskDesc =
                                        remove00(data.copyOfRange(94, 134)).toString(Charsets.UTF_8)
                                            .trim()
                                    mmkv.putString(ValueKey.CURRENT_DEVICE_NAME, taskDeviceName)
                                    mmkv.putString(ValueKey.CURRENT_TASK_NAME, taskCurrentName)
                                    mmkv.putString(ValueKey.CURRENT_TASK_DEC, taskDesc)
                                    LiveDataEvent.showTitle.value = true
                                } else {
                                    ToastUtils.show("命令校验失败")
                                }

                            }
                        } else {
                            var packageData = data.copyOfRange(0, data.size - 1)
                            var result = CRC16Utils.checkCRC(packageData)
                            if (result.toInt(16) == java.lang.Byte.toUnsignedInt(data[data.size - 1])) {
                                ToastUtils.show("查询成功")
                                taskDeviceName =
                                    remove00(data.copyOfRange(14, 54)).toString(Charsets.UTF_8)
                                        .trim()
                                taskCurrentName =
                                    remove00(data.copyOfRange(54, 94)).toString(Charsets.UTF_8)
                                        .trim()
                                taskDesc =
                                    remove00(data.copyOfRange(94, 134)).toString(Charsets.UTF_8)
                                        .trim()
                                Log.e(
                                    "测试值",
                                    "查询成功111111    " + taskDeviceName
                                )
                                mmkv.putString(ValueKey.CURRENT_DEVICE_NAME, taskDeviceName)
                                mmkv.putString(ValueKey.CURRENT_TASK_NAME, taskCurrentName)
                                mmkv.putString(ValueKey.CURRENT_TASK_DEC, taskDesc)
                                LiveDataEvent.showTitle.value = true
                            } else {
                                ToastUtils.show("命令校验失败")
                            }
                        }
                        resetClickType()
                    }
                }

                17 -> {
                    var hexResult = MyUtil.bytes2Hex(data.copyOfRange(0, 3))
                    viewModelScope.launch {
                        if ("FF55AA" == hexResult) {
                            packageDataLength = 0
                            resultDataLength = MyUtil.bytes2Hex(data.copyOfRange(3, 5)).toInt(16)
                            dataResult = ByteArray(resultDataLength + 5)
                            needFoldData = data.size < resultDataLength + 5
                        }
                        if (needFoldData) {
                            System.arraycopy(data, 0, dataResult, packageDataLength, data.size)
                            packageDataLength += data.size
                            needFoldData = packageDataLength != resultDataLength + 5
                            if (packageDataLength == resultDataLength + 5) {
                                var packageData = dataResult.copyOfRange(0, dataResult.size - 1)
                                var result = CRC16Utils.checkCRC(packageData)

                                if (result.toInt(16) == java.lang.Byte.toUnsignedInt(dataResult[dataResult.size - 1])) {
                                    clickType = 10
                                    delay(200)
                                    sendAutoTasksCMD()
                                } else {
                                    ToastUtils.show("命令校验失败")
                                }

                            }
                        } else {
                            var packageData = data.copyOfRange(0, data.size - 1)
                            var result = CRC16Utils.checkCRC(packageData)
                            if (result.toInt(16) == java.lang.Byte.toUnsignedInt(data[data.size - 1])) {
                                clickType = 10
                                delay(200)
                                sendAutoTasksCMD()
                            } else {

                                ToastUtils.show("命令校验失败")
                            }
                        }
                    }

                }

                20 -> {
                    var hexResult = MyUtil.bytes2Hex(data.copyOfRange(0, 3))
                    viewModelScope.launch {
                        if ("FF55AA" == hexResult) {
                            packageDataLength = 0
                            resultDataLength = MyUtil.bytes2Hex(data.copyOfRange(3, 5)).toInt(16)
                            dataResult = ByteArray(resultDataLength + 5)
                            needFoldData = data.size < resultDataLength + 5
                        }
                        if (needFoldData) {
                            System.arraycopy(data, 0, dataResult, packageDataLength, data.size)
                            packageDataLength += data.size
                            needFoldData = packageDataLength != resultDataLength + 5
                            if (packageDataLength == resultDataLength + 5) {
                                var packageData = dataResult.copyOfRange(0, dataResult.size - 1)
                                var result = CRC16Utils.checkCRC(packageData)

                                if (result.toInt(16) == java.lang.Byte.toUnsignedInt(dataResult[dataResult.size - 1])) {
                                    handleWorkMode(dataResult)
                                } else {
                                    ToastUtils.show("命令校验失败")
                                }

                            }
                        } else {
                            var packageData = data.copyOfRange(0, data.size - 1)
                            var result = CRC16Utils.checkCRC(packageData)
                            if (result.toInt(16) == java.lang.Byte.toUnsignedInt(data[data.size - 1])) {
                                handleWorkMode(data)
                            } else {
                                ToastUtils.show("命令校验失败")
                            }
                        }

                    }
                }

                21 -> {
                    viewModelScope.launch {
                        var hexResult = MyUtil.bytes2Hex(data.copyOfRange(0, 3))
                        var dataHex = MyUtil.bytes2Hex(data)
                        if ("FF55AA" == hexResult && dataHex.substring(14, 16).toInt(16) == 2) {
                            ToastUtils.show("操作成功")
                            LiveDataEvent.currentMode.value = LiveDataEvent.checkedWorkMode.value
                            LiveDataEvent.notifyReReadSystemInfo.value = true
                            checkNeedRereadSystemInfo()
                        }
                    }

                }

                5 -> {

                    var dataHex = MyUtil.bytes2Hex(data)
                    Log.e("校时数据", "校时数据   " + dataHex)
                    var time = formatTimeString(MyUtil.bytes2Hex(data.copyOfRange(7, 13)))
                    var timeLong = MyUtil.StrToDate(time).time
                    Log.e("设备当前时间", "  " + timeLong)
                    var currentTime = System.currentTimeMillis()
                    Log.e("手机当前时间", "  " + currentTime)
                    var minusResult = (currentTime - timeLong) / 1000
                    Log.e("相差毫秒数", "  " + minusResult)
                    if (minusResult >= -30 && minusResult <= 30) {
                        ToastUtils.show("校时成功")
                        resetClickType()
                        if (checkTimeClick == 1) {
                            if (HBluetooth.getInstance().isConnected) {
                                HBluetooth.getInstance().sender()?.let { it1 ->
                                    clickType = 18
                                    var cmd = "FF55AA000A" + getAddress() + "4501000010F90001"
                                    sendCommonCMD(
                                        it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                                    )
                                }
                            } else {
                                ToastUtils.show("请先连接设备后再操作")
                            }
                        } else if (checkTimeClick == 2) {
                            if (HBluetooth.getInstance().isConnected) {
                                HBluetooth.getInstance().sender()?.let { it1 ->
                                    clickType = 19
                                    var cmd = "FF55AA000A" + getAddress() + "4501000010F90001"
                                    sendCommonCMD(
                                        it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                                    )
                                }
                            } else {
                                ToastUtils.show("请先连接设备后再操作")
                            }
                        }
//                        MessageDialog.show(
//                            "提示", "校时成功", "确定"
//                        )
                    } else {
                        ToastUtils.show("校时失败")
                        resetClickType()
//                        MessageDialog.show(
//                            "提示", "校时失败", "确定"
//                        )
                    }

                }
            }
        }

    }

    fun remove00(data: ByteArray): ByteArray {
        var list = data.asList().toCollection(java.util.ArrayList())
        var result = ArrayList<Byte>()
        for (i in 0 until list.size) {
            if (list[i] != 0.toByte()) {
                result.add(list[i])
            }
        }

        return result.toByteArray()
    }

    fun checkNeedRereadSystemInfo() {
        if (LiveDataEvent.notifyReReadSystemInfo.value == true) {
            LiveDataEvent.notifyReReadSystemInfo.value = false
            viewModelScope.launch {
                if (HBluetooth.getInstance().isConnected) {
                    needFoldData = false
                    HBluetooth.getInstance().sender()?.let { it1 ->
                        clickType = 9
                        var cmd = "FF55AA000A" + getAddress() + "45010000000000C8"
                        sendCommonCMD(
                            it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                        )
                    }
                } else {
                    ToastUtils.show("请先连接设备后再操作")
                }
            }
        }
    }

    fun handleWorkMode(data: ByteArray) {
        viewModelScope.launch {
            Log.e("clickType", "clickType  9999 " + MyUtil.bytes2Hex(data))
            //9600波特率会分包，拆成64和一个50多的坑人
            //460800波特率 每包数据最大就有490长度，就不会分包了
            Log.e("执行了这里", "执行了这里")
            var dataHex = MyUtil.bytes2Hex(data)
            var workMode = dataHex.substring(34, 36).toInt(16)//0:空闲模式 1：离线模式 3：在线模式

            otherPackageData = data.copyOfRange(14, 210)
            otherPackageData[3] = LiveDataEvent.checkedWorkMode.value?.toByte()!!
            Log.e("clickType", "存的其它数据 " + MyUtil.bytes2Hex(otherPackageData))


            if (HBluetooth.getInstance().isConnected) {
                HBluetooth.getInstance().sender()?.let { it1 ->
                    clickType = 21
                    var workModeVale = 0
                    var cmd = "FF55AA00D2" + getAddress() + "45020000000000C8" + MyUtil.bytes2Hex(
                        otherPackageData
                    ) + "00000000"
                    sendCommonCMD(
                        it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                    )

                }
            } else {
                ToastUtils.show("请先连接设备后再操作")
            }
        }
    }

    fun handleTask(data: ByteArray) {
        viewModelScope.launch {
            Log.e("clickType", "clickType  9999 ")
            var dataHex = MyUtil.bytes2Hex(data)
            var address = dataHex.substring(28, 30).toInt(16)
            var outTime = dataHex.substring(30, 32).toInt(16)
            outTime = 30
            var intervalTime = dataHex.substring(32, 34).toInt(16)
            var workMode = dataHex.substring(34, 36).toInt(16)
            var onlineWorkTime = dataHex.substring(36, 40).toInt(16)
            var onlineWorkInterval = dataHex.substring(40, 44).toInt(16)
            var mSystemData = SystemInfoBean(
                address, outTime, intervalTime, workMode, onlineWorkTime, onlineWorkInterval
            )
            otherPackageData = data.copyOfRange(14, 22)
            Log.e("handleTask", "hanldeTask 其它数据 " + MyUtil.bytes2Hex(otherPackageData))
            LiveDataEvent.currentMode.value = otherPackageData[3].toInt()

            var json = Gson().toJson(mSystemData)
            mmkv.putString(ValueKey.SYSTEM_INFO, json)
            mmkv.putInt(ValueKey.DEVICE_ADDRESS, address)
            var packageData = dataHex.substring(44, dataHex.length)
            var startTime = packageData.substring(0, 12)
            Log.e("测试", "开始时间 " + startTime)
            var endTime = packageData.substring(12, 24)
            Log.e("测试", "结束时间 " + endTime)
            mmkv.putString(ValueKey.COLLECTION_START_TIME, formatTimeString(startTime))
            mmkv.putString(ValueKey.COLLECTION_END_TIME, formatTimeString(endTime))
            mmkv.putString(ValueKey.COLLECTION_START_TIME_CMD, startTime)
            mmkv.putString(ValueKey.COLLECTION_END_TIME_CMD, endTime)

            if (checkedWorkMode.value == 2) {
                //模式为2的时候就是压力模式，读取的是8个压力值
                var taskListData = packageData.substring(160, 224)
                waitSendTaskDataModeIs2 =
                    MyUtil.hex2Bytes(packageData.substring(24, 152))//采集间隔的8个任务参数

                waitSendTaskOtherData = MyUtil.hex2Bytes(packageData.substring(224, 376))//19个压力计算参数

                Log.e("testFun", "taskListData " + taskListData)
                var dataList: ArrayList<String> = ArrayList()
                for (i in 0 until 8) {
                    var tempString = taskListData.substring(i * 8, 8 * (i + 1))
                    dataList.add(tempString)
                }
                Log.e("testFun", "dataList " + dataList)
                var taskBeans = ArrayList<TaskBean>()
                if (dataList.size > 0) {
                    for (i in 0 until dataList.size) {
                        var taskTime = dataList.get(i).substring(0, 4).toInt(16)
                        var delayTime = dataList.get(i).substring(4, 8).toInt(16)
                        taskBeans.add(
                            TaskBean(
                                taskTime = "" + (taskTime.toFloat() / 100f),
                                delayTime = delayTime,
                                isSelected = true,
                                isRemote = true
                            )
                        )
                    }
                    tasklistData.value = taskBeans
                    delay(200)
                    queryTaskCMD()
                }
            } else {
                //模式不为2的时候就是其它模式，读取的是8个采集任务的值
                var taskListData = packageData.substring(24, 152)
                waitSendTaskOtherData =
                    MyUtil.hex2Bytes(packageData.substring(160, 376))//8个压力参数+19个压力计算参数
                Log.e("testFun", "taskListData " + taskListData)
                var dataList: ArrayList<String> = ArrayList()
                for (i in 0 until 8) {
                    var tempString = taskListData.substring(i * 16, 16 * (i + 1))
                    dataList.add(tempString)
                }
                Log.e("testFun", "dataList " + dataList)
                var taskBeans = ArrayList<TaskBean>()
                if (dataList.size > 0) {
                    for (i in 0 until dataList.size) {
                        var taskTime = dataList.get(i).substring(0, 12)
                        var year = "20" + taskTime.substring(0, 2).toInt(16)
                        var month = taskTime.substring(2, 4).toInt(16)
                        var day = taskTime.substring(4, 6).toInt(16)
                        var hour = taskTime.substring(6, 8).toInt(16)
                        var minute = taskTime.substring(8, 10).toInt(16)
                        var second = taskTime.substring(10, 12).toInt(16)
                        var taskTimeResult =
                            year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
                        var delayTime = dataList.get(i).substring(12, 16).toInt(16)
                        taskBeans.add(
                            TaskBean(
                                taskTime = MyUtil.DateToStr(MyUtil.StrToDate(taskTimeResult)),
                                delayTime = delayTime,
                                isSelected = true,
                                isRemote = true
                            )
                        )
                    }
                    tasklistData.value = taskBeans
                    delay(200)
                    queryTaskCMD()
                }

            }
        }
    }

    public fun queryTaskCMD() {
        if (HBluetooth.getInstance().isConnected) {
            HBluetooth.getInstance().sender()?.let { it1 ->
                clickType = 16
                var cmd = "FF55AA000A" + getAddress() + "4501000010300078"

                sendCommonCMD(
                    it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                )
            }
        } else {
            ToastUtils.show("请先连接设备后再操作")
        }
    }

    public fun resetClickType() {
        clickType = -1
    }


}


